<?php

namespace App\Http\Controllers;

use App\models\Admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Validator;

class AuthController extends Controller
{
    public function demo()
    {
        dd(config('app.url'));
        $data = DB::table('admin')->get();
        dd($data);
    }

    /**
     * 登录标识及操作
     * @param $admin
     */
    public function login($admin)
    {
        session('admin',$admin);
    }

    /**
     * 处理登录状况
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        $validator =  Validator::make($request->all(), [
            'admin_name' => 'required|max:255',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->err('很抱歉，您的用户名和密码不规范');
        }
        $admin = Admin::where('admin_name',$request->input('admin_name'))->first();

        if (!$admin){
            return $this->err('很抱歉，您的用户名不存在');
        }

        if ($admin && $admin->password == md5($request->input('password'))) {
            $this->login($admin);
            return $this->ok('登录成功');
        } else {
            return $this->err('很抱歉，您的密码不匹配');
        }
    }

    /**
     * 退出登录
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy(Request $request)
    {
        $request->session()->flush();  //清空所有数据
        return $this->ok('退出成功');
    }
}
